<script lang="ts" setup>
import type { SystemDeptApi } from '#/api/system/dept';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElButton, ElMessage } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { createDept, updateDept } from '#/api/system/dept';
import { $t } from '@vben/locales';

import { useSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<SystemDeptApi.SystemDept>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', [$t('system.dept.name')])
    : $t('ui.actionTitle.create', [$t('system.dept.name')]);
});

const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: useSchema(),
  showDefaultActions: false,
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues(formData.value || {});
}

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    try {
      const { valid } = await formApi.validate();
      if (!valid) return;

      modalApi.lock();

      const values = await formApi.getValues();
      console.log('formApi.getValues() 值:', values);

      if (!values || Object.keys(values).length === 0) {
        throw new Error('表单数据为空');
      }

      if (formData.value?.id) {
        const updateData = {
          ...values,
          id: formData.value.id
        };
        await updateDept(formData.value.id, updateData);
      } else {
        await createDept(values);
      }

      modalApi.close();
      ElMessage.success($t('ui.actionMessage.operationSuccess', [$t('system.dept.name')]));
      emit('success');
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error($t('ui.actionMessage.operationFailed'));
    } finally {
      modalApi.lock(false);
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<SystemDeptApi.SystemDept>();
      console.log('modalApi.getData()', data);
      if (data) {
        if (data.parentId === '0' || data.parentId === undefined) {
          data.parentId = undefined;
        }
        formData.value = {...data};

        setTimeout(() => {
          formApi.resetForm();
          if (formData.value) {
            formApi.setValues(formData.value);
          }
        }, 0);
      } else {
        formData.value = undefined;
        formApi.resetForm();
      }
    }
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" />
    <template #prepend-footer>
      <div class="flex-auto">
        <ElButton type="danger" @click="resetForm">
          {{ $t('common.reset') }}
        </ElButton>
      </div>
    </template>
  </Modal>
</template>
